﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace TimeTravel.XnaLibrary.UI
{
	/// <summary>
	/// Represents a button control.
	/// </summary>
	public class Button : TextContainer
	{
		private Texture2D mTexture;
		private Color mTintingColor = Color.White;
		private RelativeTextPosition mRelativeTextPosition;

		/// <summary>
		/// Gets or sets the texture to be used for the button.
		/// </summary>
		public Texture2D Texture
		{
			get { return mTexture; }
			set { mTexture = value; }
		}

		/// <summary>
		/// Gets or sets the color to tint the texture of the button.
		/// </summary>
		public Color TintingColor
		{
			get { return mTintingColor; }
			set { mTintingColor = value; }
		}
		
		/// <summary>
		/// Gets or sets a value indicating where the text should be placed.
		/// </summary>
		public RelativeTextPosition RelativeTextPosition
		{
			get { return mRelativeTextPosition; }
			set 
			{ 
				mRelativeTextPosition = value;
			}
		}

		/// <summary>
		/// Draws the button using the specified spritebatch. SpriteBatch.Begin must have been called prior to calling this method.
		/// </summary>
		/// <param name="spriteBatch"></param>
		public override void Draw(SpriteBatch spriteBatch)
		{
			spriteBatch.Draw(mTexture, Location, mTintingColor);

			if (Text != string.Empty && Font != null)
			{
				Vector2 absoluteTextPosition = CalculateAbsoluteTextPosition();
				spriteBatch.DrawString(Font, Text, absoluteTextPosition, TextColor);
			}
		}

		/// <summary>
		/// Calculates the absolute position of the text based on its size and relative text position.
		/// </summary>
		private Vector2 CalculateAbsoluteTextPosition()
		{
			switch (mRelativeTextPosition)
			{
				case RelativeTextPosition.Centered :
					return new Vector2(Location.Center.X - TextSize.X / 2, Location.Center.Y - TextSize.Y / 2);
				case RelativeTextPosition.CenteredAbove :
					return new Vector2(Location.Center.X - TextSize.X / 2, Location.Y);
				case RelativeTextPosition.CenteredBelow :
					return new Vector2(Location.Center.X - TextSize.X / 2, Location.Y + Location.Height);
				case RelativeTextPosition.CenteredLeft :
					return new Vector2(Location.X - TextSize.X, Location.Center.Y - TextSize.Y / 2);
				case RelativeTextPosition.CenteredRight :
					return new Vector2(Location.X + Location.Width, Location.Center.Y - TextSize.Y / 2);
				case RelativeTextPosition.TopLeft :
					return new Vector2(Location.X, Location.Y);
				default :
					throw new NotSupportedException();
			}
		}
	}
}
